let wsbasePath = "wss://rbs.xlemon.cn/wss/";
import { debounce } from './util'
import { alert, toast } from "./modal.js";
let sotk = null;
// 获取app
let app = getApp();

// 处理消息，异步请求队列
const queue = []
// 标志是否正在处理队列中的请求
let running = false

//开始webSocket
let bIm = {
  socketOpen: false,
  lockReconnect: false,
  robot_reply_failed: 0, //机器人回复失败
  limit: 0, //重连次数
  isWelcome: false, // 是否下发欢迎语
  isReconnect: false, // 是否切后台后重连
  timePush: null, // 接收到消息后，1s后塞消息进入队列
  webSocketStart(e) {
    sotk = wx.connectSocket({
      url: wsbasePath,
      success: (res) => {
        console.log("小程序连接成功：", res);
        this.webSokcketMethods();
      },
      fail: (err) => {
        console.log("出现错误啦！！" + err);
        toast("网络异常！");
      },
    });
  },
  webSokcketMethods(e) {
    let that = this;
    console.log('webSokcketMethods succ')
    wx.onSocketMessage((res) => {
      try {
        const data = JSON.parse(res.data);
        if (data.type == 201) {
          // 服务端心跳
          that.sendSocketMessage({
            type: 200,
            content: "",
          });
        } else {
          if (!!data.robot_reply_failed) {
            that.robot_reply_failed = data.robot_reply_failed
          } else {
            that.addQueue(() => that.requestData(data))

            // const chatList = JSON.parse(JSON.stringify(app.globalData.chatList))
            // // 如果此时最后一条消息类型为11，问题是否解决，则不再继续追加反馈模块
            // if (data.type == 11 && chatList[chatList.length - 1].type == 11) return;
            // data.create_time = data.create_time || Date.parse(new Date()) / 1000
            // data.is_history = 0
            // chatList.push(data)
            // app.globalData.chatList = chatList
          }
        }
      } catch (e) {
        console.log("返回消息异常", res.data);
      }
    });
    wx.onSocketOpen(() => {
      that.socketOpen = true;
      console.log("WebSocket连接打开 ",);
      if (!that.isWelcome && that.socketOpen) {
        that.isWelcome = true;
        // 下发欢迎语,纯前端下发
        const chatList = JSON.parse(JSON.stringify(app.globalData.chatList))
        chatList.push({
          type: 1,
          content: { content: "您好，我是您的安全染发顾问-蜀哥，有任何染发相关问题都可以直接咨询我。\n以下是一些您可能关心的问题，直接点击选择即可查看哦。" },
          from: "bot",
          create_time: Date.parse(new Date()) / 1000,
        })
        app.globalData.chatList = chatList
        setTimeout(() => {
          // 202 代表 welcome
          that.sendSocketMessage({
            type: 202,
            content: {},
          });
        }, 1000);
      }

      if (that.isReconnect) {
        toast("已成功接入客服系统");
      }
    });
    wx.onSocketError((res) => {
      that.socketOpen = false;
      console.log("WebSocket连接打开失败");
      that.reconnect();
    });
    wx.onSocketClose((res) => {
      that.socketOpen = false;
      console.log("WebSocket 已关闭！");
      that.reconnect();
    });

  },
  // 通过setTimeout模拟异步请求
  requestData(data) {
    return new Promise(function (resolve) {
      setTimeout(() => {
        resolve(data)
      }, 1000)
    })
  },
  addQueue(item) {
    queue.push(item)
    if (queue.length > 0 && !running) {
      running = true
      this.process()
    }
  },
  process() {
    const item = queue.shift()
    if (item) {
      item().then(data => {
        // console.log('已处理事件' + data)
        const chatList = JSON.parse(JSON.stringify(app.globalData.chatList))
        // 如果此时最后一条消息类型为11，问题是否解决，则不再继续追加反馈模块
        if (data.type == 11 && chatList[chatList.length - 1].type == 11) return;
        data.create_time = data.create_time || Date.parse(new Date()) / 1000
        data.is_history = 0
        chatList.push(data)
        app.globalData.chatList = chatList
        this.process()
      })
    } else {
      running = false
    }
  },

  //发送消息
  sendSocketMessage: debounce(function (msgData, filePath, duration) {
    let that = this;
    if (that.socketOpen) {
      // console.log('通过 WebSocket 连接发送数据', msgData)
      if (that.robot_reply_failed) {
        msgData.robot_reply_failed = that.robot_reply_failed
      }
      // sotk.send(
      wx.sendSocketMessage({
        data: JSON.stringify({
          ...msgData,
          token: wx.getStorageSync("access_token") || "",
        }),
        success: function (res) {
          // 心跳：200  202: 链接成功  反馈：203  上报新手引导：204   都不追加消息
          if (msgData.type !== 200 && msgData.type !== 202 && msgData.type !== 203 && msgData.type !== 204) {
            const chatList = JSON.parse(JSON.stringify(app.globalData.chatList))
            if (msgData.type == 2 || msgData.type == 3 || msgData.type == 4) {
              if (msgData.type == 2) {
                msgData.content.duration = duration
              }
              msgData.content.url = filePath
            }
            if (!!Object.keys(msgData.content).length || !!msgData.content?.content.length) {
              chatList.push({
                ...msgData,
                from: "user",
                create_time: Date.parse(new Date()) / 1000,
              })
              app.globalData.chatList = chatList
            }

          }
          // console.log("已发送", res);
        },
      });
    } else {
      that.reconnect();
      that.isReconnect = true;
      toast("链接已断开，正在重连～");
      console.log("链接已断开，请重试")
    }
  }, 500),
  //关闭连接
  closeWebsocket(str) {
    let that = this;
    if (that.socketOpen) {
      sotk.close({
        code: "1000",
        reason: str,
        success: function () {
          console.log("成功关闭websocket连接");
        },
      });
    }
  },

  //重新连接
  reconnect() {
    var that = this;
    if (that.lockReconnect) return;
    that.lockReconnect = true;
    clearTimeout(that.timer);
    if (that.limit < 3) {
      //连接3次后不再重新连接
      that.timer = setTimeout(() => {
        that.webSocketStart();
        that.lockReconnect = false;
        console.log("次数:" + that.limit);
      }, 5000); //每隔5秒连接一次
      that.limit = that.limit + 1;
    }
  }
};

export default bIm;
